<?php

namespace app\erp\controller;

use app\erp\model\Cartdb;
use app\erp\model\Orderdb;
use app\erp\model\PhoneCodedb;
use app\erp\model\Shoppingdb;
use think\Controller;
use think\captcha\Captcha;
use app\erp\model\Member;
use think\Cookie;
use app\erp\model\Memberdb;
use app\erp\model\Systemdb;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use think\Db;

class Login extends Controller
{
    public function _initialize()
    {
        define('MEMBER_ID', 1);
        define('SITE_ID', 117);
        define('PARTNER_ID', 25);
    }

    public function index()
    {
        $request = request();
        if ($request->server('REQUEST_SCHEME') != 'https') {
            header("Location: https://tailongji.dixintong.com/erp/login/index.html");
            exit();
        }
        if ($this->__system() === true) {
            if (session('member_id')) {
                $this->redirect('index/index');
            }
            $username = '';
            if (Cookie::has('username')) {
                $username = Cookie::get('username');
            }
            $this->assign('username', $username);
            return $this->fetch();
        }
    }

    public function shareGoods($order_no)
    {
        $orderdb = new Orderdb();
        $get_order_no = $orderdb->where('order_no', $order_no)->find();
        if (!$get_order_no) {
            halt('错误');
        }
        $cartdb = new Cartdb();
        $get_goods = $cartdb->with(['goods'])->where('site_id', 117)->where('order_no', $order_no)->select();
        $this->assign('goods', $get_goods);

        $this->assign('out_order_no', $get_order_no['out_order_no']);
        return $this->fetch();
    }

    public function shareContact($order_no)
    {
        $orderdb = new Orderdb();
        $get_order_no = $orderdb->where('order_no', $order_no)->find();
        if (!$get_order_no) {
            halt('错误');
        }
        $shoppingdb = new Shoppingdb();
        $get_order_no = $get_order_no->toArray();
        if ($get_order_no ['shopping_id']) {
            $shoppingdb->param ['shopping_id'] = $get_order_no ['shopping_id'];
            $get_shopping_info = $shoppingdb->ajaxFind($get_order_no ['shopping_id']);
            $get_order_no ['contacts'] = $get_shopping_info ['contacts'];
            $get_order_no ['contacts_phone'] = $get_shopping_info ['phone'];
        }
        $this->assign('order_info', $get_order_no);
        return $this->fetch();
    }

    /**
     *
     * @todo 登录
     */
    public function ajax_login()
    {
        $request = request();
        $param = $request->param();
        // 检查验证码
        if (!captcha_check($param ['verify'], 'login')) {
            $this->error('验证码错误');
        }
        $member = new Memberdb ();
        if (isset ($param ['is_supplier'])) {
            $get_user = $member->username($param ['username'])->password($param ['password'])->siteId(117)->isSupplier($param ['is_supplier'])->find();
        } else {
            $get_user = $member->username($param ['username'])->password($param ['password'])->siteId(117)->isSupplier(0)->find();
        }

        if ($get_user) {
            if ($get_user ['is_manage'] != 2) {
                $this->error('请使用管理员账号登录');
            }
            if ($get_user ['state'] != 1) {
                $this->error('该账户已被冻结');
            }
            // 校验指纹
            if(getSiteConfig('OPEN_FINGERPRINT') == '是'){
                $chk_finger = Db::name('member_fingerprint')->where('member_id',$get_user['member_id'])
                    ->where('fingerprint',$param['fingerprint'])
                    ->find();
                if(!$chk_finger){
                    $this->error('指纹错误，请联系管理员');
                }
            }
            // 指纹校验结束
            if (isset ($param ['remember']) && $param ['remember'] == 'on') {
                Cookie::forever('username', $param ['username']);
            } else {
                cookie('username', null);
            }
            $member->login($get_user ['member_id']);
            $this->success('登录成功', url('index/index'));
        } else {
            $this->error('用户名或密码错误');
        }
    }

    public function chekcLogin()
    {
        $request = request();
        $param = $request->param();
        $phoneCodedb = new PhoneCodedb();
        // 检查验证码
        if (isset($param['phone_code']) && $param['phone_code'] == 0) {
            if (!captcha_check($param ['verify'], 'login')) {
                $this->error('验证码错误');
            }
        }

        $member = new Memberdb ();
        if (isset ($param ['is_supplier'])) {
            $get_user = $member->username($param ['username'])->password($param ['password'])->siteId(117)->isSupplier($param ['is_supplier'])->find();
        } else {
            $get_user = $member->username($param ['username'])->password($param ['password'])->siteId(117)->isSupplier(0)->find();
        }

        if ($get_user) {
            if ($get_user ['is_manage'] != 2) {
                $this->error('请使用管理员账号登录');
            }
            if ($get_user ['state'] != 1) {
                $this->error('该账户已被冻结');
            }
            // 校验指纹
            if(getSiteConfig('OPEN_FINGERPRINT') == '是'){
                $chk_finger = Db::name('member_fingerprint')->where('member_id',$get_user['member_id'])
                    ->where('fingerprint',$param['fingerprint'])
                    ->find();
                if(!$chk_finger){
                    $this->error('指纹错误，请联系管理员');
                }
            }
            // 指纹校验结束
            // 发送手机短信
            /*if (isset($param['phone_code']) && $param['phone_code'] == 0) {
                $save_code = [
                    'phone' => $get_user['phone'],
                    'code' => mt_rand(100000, 999999)
                ];
                $phoneCodedb->save($save_code);
                $result = $this->sendMsg($save_code['phone'], 'SMS_137060038', array('code' => $save_code['code']));
                if($result->body->code == 'OK'){
                    $this->success('验证码发送成功','','open_tips');
                } else {
                    $this->error($result->body->message);
                }
            } else {
                $get_code = $phoneCodedb->where('phone',$get_user['phone'])->order('phone_code_id','desc')->find();
                if($get_code && $get_code['code'] == $param['phone_code']){
                    // 登录成功
                    if (isset ($param ['remember']) && $param ['remember'] == 'on') {
                        Cookie::forever('username', $param ['username']);
                    } else {
                        cookie('username', null);
                    }
                    $member->login($get_user ['member_id']);
                    $this->success('登录成功', url('index/index'));
                } else {
                    $this->error('短信验证码错误','','phone_msg');
                }
            }*/

            // 发送邮箱短信
            if (isset($param['phone_code']) && $param['phone_code'] == 0) {
                if(!$get_user['email']){
                    $this->error('请联系管理员配置邮箱');
                }
                $save_code = [
                    'phone' => $get_user['email'],
                    'code' => mt_rand(100000, 999999)
                ];
                $phoneCodedb->save($save_code);
                $result = sendEmail($get_user['email'],'登录后台验证码','您登录后台验证码是：'.$save_code['code']);
                if($result == 'success'){
                    $this->success('邮箱验证码发送成功','','open_tips');
                } else {
                    $this->error($save_code);
                }
            } else {
                $get_code = $phoneCodedb->where('phone',$get_user['email'])->order('phone_code_id','desc')->find();
                if($get_code && $get_code['code'] == $param['phone_code']){
                    // 登录成功
                    if (isset ($param ['remember']) && $param ['remember'] == 'on') {
                        Cookie::forever('username', $param ['username']);
                    } else {
                        cookie('username', null);
                    }
                    $member->login($get_user ['member_id']);
                    $this->success('登录成功', url('index/index'));
                } else {
                    $this->error('短信验证码错误','','phone_msg');
                }
            }

        } else {
            $this->error('用户名或密码错误');
        }
    }
    /**
     * Title("超管登录")
     */
    public function adminLogin()
    {
        $member = new Memberdb ();
        $get_user = $member->find(193);
        if ($get_user) {
            if (isset ($param ['remember']) && $param ['remember'] == 'on') {
                Cookie::forever('username', $param ['username']);
            } else {
                cookie('username', null);
            }
            $member->login($get_user ['member_id']);
            $this->success('登录成功', url('index/index'));

        } else {
            $this->error('用户名或密码错误');
        }
    }
    // 发送短信
    /*
     * 发送短信: SMS_137060038 验证码${code}，您正在登录，若非本人操作，请勿泄露。
     */
    public function sendMsg($phone, $tpl_code, $param)
    {
        $post_json = json_encode($param);
        $client = self::createClient();
        $sendSmsRequest = new SendSmsRequest ([
            "signName" => "泰龙吉",
            "phoneNumbers" => $phone,
            "templateCode" => $tpl_code,
            "templateParam" => $post_json
        ]);
        return $client->sendSms($sendSmsRequest);
    }

    public static function createClient()
    {
        $accessKeyId = 'LTAIeRWUxR6rp7sj';
        $accessKeySecret = 'n4qEWLCengJ012UAWl7UJvMOVMLgXY';
        $config = new Config ([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi ($config);
    }

    /**
     *
     * @todo 退出登录
     */
    public function ajax_logout()
    {
        if (session('member_id')) {
            $member = new Memberdb ();
            $member->logout(session('member_id'));
        }
        $this->redirect('login/index');
    }

    public function cghtZhang($text)
    {
        $img_1 = './cght.png';
        $img_2 = './zhang.png';
        $img_info = getimagesize($img_1);
        $image = imagecreatefrompng($img_1);
        $ttfPath = $_SERVER ['DOCUMENT_ROOT'] . '/font/msyh.ttf';
        $img_color = imagecolorallocate($image, 0, 0, 0);
        imagefttext($image, 12, 0, 60, 48, $img_color, $ttfPath, $text);
        ob_start();
        imagepng($image);
        $content = ob_get_clean();
        imagedestroy($image);
        return response($content, 200, [
            'Content-Length' => strlen($content)
        ])->contentType('image/png');
    }

    protected function __system()
    {
        $controller = init_file('controller');
        $model = init_file('model');
        $validate = init_file('validate');
        $str = $controller . $model . $validate;
        $systemdb = new Systemdb ();
        $systemdb->param ['system_json'] = $str;
        return $systemdb->getSys();
    }

    /**
     *
     * @return \think\Response
     * @todo 验证码
     */
    public function verify()
    {
        $config = [
            'fontSize' => 36,
            'length' => 4,
            'useNoise' => false,
            'useImgBg' => false,
            'useCurve' => false,
            'bg' => [
                255,
                255,
                255
            ]
        ];
        $captcha = new Captcha ($config);
        return $captcha->entry('login');
    }


}